import services from '@/services/menus';
import {ActionType, Key, PageContainer, ProColumns, ProFormSelect, ProTable,} from '@ant-design/pro-components';
import {Button, Divider, message, Modal} from 'antd';
import React, {useEffect, useRef, useState} from 'react';
import CreateForm from '@/components/CreateForm';
import EditForm, {FormValueType} from './components/EditForm';

const {select, add, enabled, deleteByCodes, disable, alter, tree, getChild} = services.MenuController;


/**
 * 新增菜单
 * @param fields
 */
const handleAdd = async (fields: API.MenuAdd, childPparent: { parentCode: string; parentName: string; }) => {
    const hide = message.loading('正在添加');
    try {
        const addFields = {...fields}
        if (childPparent) {
            addFields.parentCode = childPparent.parentCode;
            addFields.parentName = childPparent.parentName;
        }
        // console.log("addFields:", addFields)
        await add(addFields);
        hide();
        message.success('添加成功');
        return true;
    } catch (error) {
        hide();
        // message.error('添加失败请重试！');
        return false;
    }
};

/**
 *  删除菜单
 * @param id
 */
const handleRemove = async (code: string) => {
    const hide = message.loading('正在删除');
    if (!code) return true;
    try {
        await deleteByCodes([code]);
        hide();
        message.success('删除成功');
        return true;
    } catch (error) {
        hide();
        //   message.error('删除失败，请重试');
        return false;
    }
};


/**
 * 编辑菜单
 * @param fields
 */
const handleUpdate = async (fields: FormValueType) => {
    const hide = message.loading('正在编辑');
    try {
        console.log("fields:", fields)
        await alter({...fields} as API.MenuAlter);
        hide();
        message.success('编辑成功');
        return true;
    } catch (error) {
        hide();
        // message.error('添加失败请重试！');
        return false;
    }
};


const TableList: React.FC<unknown> = () => {
    const actionRef = useRef<ActionType>();
    const [editModalVisible, handleEditModalVisible] = useState<boolean>(false);
    const [stepFormValues, setStepFormValues] = useState({});
    const [addMenuFormValues, setAddMenuFormValues] = useState({
        parentCode :"menu",
        parentName :"主菜单",
    });
    // 分页
    const [current, setCurrent] = useState(1); // 当前页码
    const [pageSize, setPageSize] = useState(10); // 每页显示条数
    // 新增
    const [createModalVisible, handleModalVisible] = useState<boolean>(false);
    const [expandedRowKeys, setExpandedRowKeys] = useState<React.Key[]>([]);

    // 初始化
    useEffect(() => {
    }, []);

    const typeValueEnum = {
        0: {text: '节点', type: "0"},
        1: {text: '功能', type: "1"},
        2: {text: '按钮', type: "2"},
    };

    const statusValueEnum = {
        0: {text: '禁用', type: "0"},
        1: {text: '启用', type: "1"},
    }

    // 子集
    const expandedRowRender = (record: API.MenuVO) => {
        return (
          <ProTable<API.MenuVO>
            // 想在子菜单中保留某些列但不显示其他列，可以在 columns 过滤中进行更细致的控制
            columns={columns.filter(col => col.dataIndex !== 'children')}
            headerTitle={false} // 移除标题
            showHeader={false} // 隐藏表头
            search={false}
            rowKey="id"
            options={false}
            params={{ parentCode: record.code }} // // 根据父级 code 加载子菜单
            request={async (params) => {
              const { data, success } = await getChild({code:params.parentCode});
              return {
                data: data || [],
                success,
              };
            }}
            pagination={false}
            expandable={{
              expandedRowKeys,
              onExpandedRowsChange: (expandedKeys: readonly Key[]) => {
                setExpandedRowKeys([...expandedKeys]);
              },
              expandedRowRender, // 递归调用自身
            }}
          />
        );
      };

      // 列表数据接口
    const columns: ProColumns<API.MenuVO>[] = [
        {
            title: 'id',
            dataIndex: 'id',
            tooltip: '唯一的 key',
            hideInForm: true,
            hideInTable: true,
            search: false
        },
        {
            title: '排序',
            dataIndex: 'sort',
            valueType: 'text',
            hideInForm: true,
            search: false,
        },
        {
            title: '菜单名',
            dataIndex: 'name',
            valueType: 'text',
            formItemProps: {
                rules: [{required: true, message: '请输入名称'}],
            },
        },
        {
            title: '菜单Code',
            dataIndex: 'code',
            valueType: 'text',
            // hideInForm: true,
            hideInTable: true,
            search: false,
            formItemProps: {
                rules: [{required: true, message: '请输入编号'}],
            },
        },

        {
            title: '菜单组件',
            dataIndex: 'component',
            valueType: 'text',
            search: false,
            formItemProps: {
                rules: [{required: false, message: '请输入菜单组件'}],
            },
        },
        {
            title: '菜单图标',
            dataIndex: 'icon',
            valueType: 'text',
            search: false,
            formItemProps: {
                rules: [{required: false, message: '请输入菜单图标'}],
            },
        },
        {
            title: '菜单路由',
            dataIndex: 'router',
            valueType: 'text',
            search: false,
            formItemProps: {
                rules: [{required: false, message: '请输入菜单路由'}],
            },
        },
        {
            title: '父级Code',
            dataIndex: 'parentCode',
            hideInForm: true,
            hideInTable: true,
            valueType: 'text',
            search: false,
            formItemProps: {
                rules: [{required: false, message: '请输入父级Code'}],
            },
        },
        {
            title: '父级名称',
            dataIndex: 'parentName',
            hideInForm: true,
            hideInTable: true,
            valueType: 'text',
            search: false,
            formItemProps: {
                rules: [{required: false, message: '请输入父级名称'}],
            },
        },
        {
            title: '菜单类型',
            dataIndex: 'type',
            valueType: 'text',
            valueEnum: typeValueEnum,
            formItemProps: {
                rules: [{required: true, message: '请选择类型'}],
            },
            search: {
                transform: (value) => (value === '1' ? 1 : value === '2' ? 2 : 0), // Assuming the search transform is needed
            },
            // Default value for the form
            renderFormItem: (item, {type, defaultRender, ...rest}, form) => {
                if (type === 'form') {
                    // Apply default value only for the form, not search
                    return (
                        <ProFormSelect
                            {...rest}
                            valueEnum={typeValueEnum}
                            fieldProps={{
                                defaultValue: "0",
                                placeholder: '请选择类型',
                            }}
                        />
                    );
                }
                return defaultRender(item);
            },
        },
        {
            title: '菜单状态',
            dataIndex: 'status',
            valueType: 'text',
            valueEnum: statusValueEnum,
            formItemProps: {
                rules: [{required: true, message: '请选择节点状态'}],
            },
            search: {
                transform: (value) => (value === "1" ? 1 : 0),
            },
            // Default value for the form
            renderFormItem: (item, {type, defaultRender, ...rest}, form) => {
                if (type === 'form') {
                    // Apply default value only for the form, not search
                    return (
                        <ProFormSelect
                            {...rest}
                            valueEnum={statusValueEnum}
                            fieldProps={{
                                defaultValue: "1",
                                placeholder: '请选择节点状态',
                            }}
                        />
                    );
                }
                return defaultRender(item);
            },
        },
        {
            title: '操作',
            dataIndex: 'option',
            valueType: 'option',
            render: (_, record) => (
                <>
                    <a
                        onClick={() => {
                            Modal.confirm({
                                title: '确认删除',
                                content: `确定要删除任务 ${record.name} 吗？`,
                                okText: '确认',
                                okType: 'danger',
                                cancelText: '取消',
                                onOk: async () => {
                                    const success = await handleRemove(record.code);
                                    ;
                                    if (success) {
                                        actionRef.current?.reloadAndRest?.();
                                    }
                                },
                            });
                        }}
                    >
                        删除
                    </a>
                    <Divider type="vertical"/>
                    <a
                        onClick={() => {
                            handleEditModalVisible(true);
                            setStepFormValues(record);
                        }}
                    >
                        编辑
                    </a>
                    <Divider type="vertical"/>
                    <a
                        onClick={() => {
                            handleModalVisible(true);
                            setAddMenuFormValues({
                                parentCode:record.code,
                                parentName:record.name?record.name:"",
                            });
                        }}
                    >
                        新增子菜单
                    </a>
                    <Divider type="vertical"/>
                    <a
                        key="expand"
                        onClick={() => {
                        setExpandedRowKeys(prevKeys =>
                            prevKeys.includes(record.id)
                            ? prevKeys.filter(key => key !== record.id)
                            : [...prevKeys, record.id]
                        );
                        }}
                    >
                        {expandedRowKeys.includes(record.id) ? '收起' : '展开'}
                    </a>

                </>
            ),
        },
    ];

    return (
        <PageContainer
            header={{
                title: '',
            }}
        >
            <ProTable<API.MenuVO>
                    headerTitle="查询菜单"
                    actionRef={actionRef}
                    rowKey="id"
                    search={{
                        labelWidth: 120,
                    }}
                    toolBarRender={() => [
                        <Button
                            key="1"
                            type="primary"
                            onClick={() => handleModalVisible(true)}
                        >
                            新增主菜单
                        </Button>,
                    ]}
                    pagination={{
                        current, // 当前页码
                        pageSize, // 每页条数
                        showSizeChanger: true, // 是否可以改变 pageSize
                        pageSizeOptions: ['5', '10', '20', '50'], // 自定义每页条数下拉选项
                        onChange: (page, pageSize) => { // 页码或 pageSize 改变的回调。
                            setCurrent(page);
                            setPageSize(pageSize);
                        },
                        onShowSizeChange: (current, size) => {// pageSize 改变的回调。
                            setCurrent(current);
                            setPageSize(size);
                        },
                    }}
                    // , sorter, filter
                    request={async (params) => {
                        const finds: API.MenuPage = {
                            name: params.name,
                            status: params.status,
                            parentCode: params.parentCode || "menu",
                            page: {
                                pageIndex: params.current,
                                pageSize: params.pageSize,
                            },
                        };
                        const {data, success} = await select({
                            ...finds,
                            // FIXME: remove @ts-ignore
                            // @ts-ignore
                            // sorter,
                            // filter,
                        });
                        return {
                            data: data?.rows || [],
                            total: data?.total,
                            pageSize: data?.pageSize,
                            current: data?.currentPage,
                            success,
                        };
                    }}
                    expandable={{
                        expandedRowKeys,
                        onExpandedRowsChange: (expandedKeys: readonly Key[]) => {
                          setExpandedRowKeys([...expandedKeys]);
                        },
                        expandedRowRender,
                    }}
                    columns={columns}
            />
            <CreateForm
                onCancel={() => handleModalVisible(false)}
                modalVisible={createModalVisible}
            >
                <ProTable<API.MenuVO, API.MenuAdd>
                    onSubmit={async (value) => {
                        const success = await handleAdd(value, addMenuFormValues);
                        setAddMenuFormValues({
                             parentCode :"menu",
                            parentName :"主菜单",
                        });
                        if (success) {
                            handleModalVisible(false);
                            if (actionRef.current) {
                                actionRef.current.reload();
                            }
                        }
                    }}
                    rowKey="id"
                    type="form"
                    columns={columns}
                    form={{
                        initialValues: {
                            type: "0",  // 设置类型的默认值
                            status: "1" // 设置节点状态的默认值
                        }
                    }}
                />
            </CreateForm>

            {stepFormValues && Object.keys(stepFormValues).length ? (
                <EditForm
                    onSubmit={async (value) => {
                        const success = await handleUpdate(value);
                        if (success) {
                            handleEditModalVisible(false);
                            setStepFormValues({});
                            if (actionRef.current) {
                                actionRef.current.reload();
                            }
                        }
                    }}
                    onOpenChange={(visible) => {
                        if (!visible) {
                            handleEditModalVisible(false);
                            setStepFormValues({});
                        }
                    }}
                    editModalVisible={editModalVisible}
                    values={stepFormValues}
                    statusValueEnum={statusValueEnum}
                    typeValueEnum={typeValueEnum}
                />
            ) : null}
        </PageContainer>
    );
};

export default TableList;
